using System;
using System.Windows.Forms;
using System.Drawing;
using System.Windows.Threading;

namespace DesktopWidgetApp.Client.Services
{
    /// <summary>
    /// 托盘图标管理器
    /// 简化版本，提供基本的托盘图标和通知功能
    /// </summary>
    public class TrayIconManager
    {
        private NotifyIcon? _trayIcon;
        private readonly Dispatcher _dispatcher;

        /// <summary>
        /// 构造函数
        /// </summary>
        public TrayIconManager()
        {
            // 获取当前UI线程的调度器
            _dispatcher = Dispatcher.CurrentDispatcher;
        }

        /// <summary>
        /// 更新托盘图标状态
        /// </summary>
        /// <param name="status">用户状态</param>
        public void UpdateTrayIconStatus(UserStatus status)
        {
            // 在UI线程上执行
            _dispatcher.Invoke(() =>
            {
                // 确保托盘图标已初始化
                if (_trayIcon == null)
                {
                    InitializeTrayIcon();
                }

                if (_trayIcon == null)
                {
                    return;
                }

                // 根据状态设置图标
                if (status.IsDoNotDisturb)
                {
                    _trayIcon.Text = "请勿打扰模式已开启";
                }
                else
                {
                    _trayIcon.Text = "正常模式";
                }
            });
        }

        /// <summary>
        /// 显示通知
        /// </summary>
        /// <param name="title">通知标题</param>
        /// <param name="message">通知内容</param>
        public void ShowNotification(string title, string message)
        {
            // 在UI线程上执行
            _dispatcher.Invoke(() =>
            {
                // 确保托盘图标已初始化
                if (_trayIcon == null)
                {
                    InitializeTrayIcon();
                }

                // 显示通知
                _trayIcon.ShowBalloonTip(3000, title, message, ToolTipIcon.Info);
            });
        }

        /// <summary>
        /// 初始化托盘图标
        /// </summary>
        private void InitializeTrayIcon()
        {
            _trayIcon = new NotifyIcon
            {
                Icon = SystemIcons.Application,
                Visible = true,
                Text = "桌面小部件应用"
            };

            // 创建退出菜单项
            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("退出", null, (s, e) =>
            {
                _trayIcon.Dispose();
                System.Windows.Application.Current.Shutdown();
            });

            _trayIcon.ContextMenuStrip = contextMenu;
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        public void Dispose()
        {
            if (_trayIcon != null)
            {
                _trayIcon.Visible = false;
                _trayIcon.Dispose();
                _trayIcon = null;
            }
        }
    }
}